package com.dji.compose_learning.net

import androidx.paging.PagingSource
import androidx.paging.PagingState

/**
 * 自定义的pagingsource
 */
class MyPagingSource(
    val githubService: GithubService= getGithubService(),
    val words:String
):PagingSource<Int,InfoItem>() {
    override fun getRefreshKey(state: PagingState<Int, InfoItem>): Int? {
        return state.anchorPosition?.let {
            val anchorPage = state.closestPageToPosition(it)
            anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1)
        }
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, InfoItem> {
        return try {
            val nextPage: Int = params.key ?: 1
            val repositorRst = githubService.searchRepositors(words, nextPage, 20)
            LoadResult.Page(
                data = repositorRst.items,
                prevKey = if (nextPage == 1) null else nextPage - 1,
                nextKey = if (repositorRst.items.isEmpty()) null else nextPage + 1
            )
        }catch (e:Exception){
            LoadResult.Error(e)
        }
    }

}